<?php
namespace App\Libs\TencentCloud;
use GuzzleHttp\Client;
use Redis;
use Hashids;

class FaceIdentify{
    protected $app_id = null;
    protected $app_secret = null;

    public function __construct($app_id=null,$secret=null)
    {
        $this->app_id = $app_id?$app_id:env('TENCENT_FACE_APPID');
        $this->app_secret = $secret?$secret:env('TENCENT_FACE_SECRET');
    }

    public function getAccessToken() {
       $acces_token = Redis::get('access_token:'.$this->app_id);
       if($acces_token) {
           return $acces_token;
       }
       $http_client = new Client();
       $res = $http_client->request('GET','https://idasc.webank.com/api/oauth2/access_token',['query'=>[
           'app_id'=>$this->app_id,
           'secret'=>$this->app_secret,
           'grant_type'=>'client_credential',
           'version'=>'1.0.0'
       ]]);
       $response = json_decode($res->getBody()->getContents(),true);
       if($response && $response['code']==0) {
           Redis::setex('access_token:'.$this->app_id,$response['expire_in']-200,$response['access_token']);
           return $response['access_token'];
       }
       \Log::error('get access_token error:'.json_encode($response));
       return false;
    }

    public function getApiTicket($user_id) {
        $client = new Client();
        $response = $client->request('GET','https://idasc.webank.com/api/oauth2/api_ticket',['query'=>[
            'app_id'=>$this->app_id,
            'access_token'=>$this->getAccessToken(),
            'type'=>'NONCE',
            'version'=>'1.0.0',
            'user_id'=>$user_id
        ]]);
        $res = json_decode($response->getBody()->getContents(),true);
        if($res && $res['code'] == 0) {
            return $res['tickets'][0]['value'];
        }
        \Log::error('get api ticket:'.json_encode($res));
        return false;
    }

    public function getSignature($uid,$nonce) {
        $arr = [
            'wbappid'=>$this->app_id,
            'userId'=>$uid,
            'nonceStr'=>$nonce,
            'version'=>'1.0.0',
            'ticket'=>$this->getApiTicket($uid)
        ];
        //var_dump($arr);
        $arr_val = array_values($arr);
        sort($arr_val,SORT_STRING);
        //var_dump($arr_val);
        $str = implode('',$arr_val);
        //var_dump($str);
        return sha1($str);
    }

    public function uploadUserInfo($order_no,$name,$idNo,$userId,$nonce) {
        $sign = $this->getSignature($userId,$nonce);
        $client = new Client();
        $post_data = array(
            'webankAppId'=>$this->app_id,
            'orderNo'=>$order_no,
            'name'=>$name,
            'idNo'=>$idNo,
            'userId'=>$userId,
            'version'=>'1.0.0',
            'sign'=>$sign
        );
       $response =  $client->request('POST','https://idasc.webank.com/api/server/getfaceid',['json'=>$post_data]);
       $res = json_decode($response->getBody()->getContents(),true);
       if($res && $res['code']==0) {
           $res['result']['sign'] = $sign;
           return $res['result'];
       }
       \Log::error('get faceid failed:'.json_encode($res));
       return false;
    }

    public function getNonceStr() {
        $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
        $name=substr(str_shuffle($strs),mt_rand(0,strlen($strs)-33),32);
        return $name;
    }
}
